<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <title>Keycloak OIDC Demo</title>
        <link
            href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"
            rel="stylesheet"
            integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk"
            crossorigin="anonymous"
        />
        <script src="http://localhost:9000/js/keycloak.js"></script>
        <style>
            #logout.hidden {
                display: none;
            }
        </style>
    </head>
    <body>
        <div class="container">
            <h1>Keycloak Auth Demo</h1>
            <h2 class="mt-4">Welcome to << corporate intranet >></h2>
            <p class="lead">
                You are <span id="auth-status"></span>
                <button class="btn btn-sm btn-secondary hidden" id="logout">Log out of intranet</button>
            </p>
            <div class="text-center mt-4">
                <button id="login" class="btn btn-primary">Log In To Vendure</button>
            </div>
        </div>
        <script>
            const loginButton = document.querySelector('#login');
            const logoutButton = document.querySelector('#logout');
            const authStatus = document.querySelector('#auth-status');

            const keycloak = new Keycloak({
                realm: 'myrealm',
                'auth-server-url': 'http://localhost:9000/auth/',
                'ssl-required': 'external',
                resource: 'vendure',
                'public-client': true,
                'confidential-port': 0,
                clientId: 'vendure',
                flow: 'standard',
            });

            keycloak
                .init({
                    onLoad: 'check-sso',
                })
                .then(function (authenticated) {
                    console.log('authenticated', authenticated);
                    authStatus.innerHTML = authenticated ? `logged in` : `not logged in`;
                    if (authenticated) {
                        if (-1 < window.location.search.indexOf('loginToVendure')) {
                            loginToAdminUi();
                        }
                        logoutButton.classList.remove('hidden');
                    } else {
                        logoutButton.classList.add('hidden');
                    }

                    logoutButton.addEventListener('click', () => {
                        keycloak.logout();
                    });

                    loginButton.addEventListener('click', () => {
                        if (authenticated) {
                            loginToAdminUi();
                        } else {
                            keycloak.login({
                                redirectUri: window.location.href + '?loginToVendure=true',
                            });
                        }
                    });
                })
                .catch(function () {
                    alert('failed to initialize');
                });

            function loginToAdminUi() {
                return graphQlQuery(
                    /* GraphQL */ `
                        mutation Authenticate($token: String!) {
                            authenticate(input: { keycloak: { token: $token } }) {
                                ... on CurrentUser {
                                    id
                                }
                                ... on ErrorResult {
                                    errorCode
                                    message
                                }
                            }
                        }
                    `,
                    { token: keycloak.token },
                )
                    .then(result => {
                        console.log(result);
                        if (result.data?.authenticate.id) {
                            // successfully authenticated
                            window.location.replace('http://localhost:4200/admin');
                        }
                    })
                    .catch(err => {
                        console.log('error', err);
                    });
            }

            function graphQlQuery(query, variables) {
                return fetch('http://localhost:3000/admin-api', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        Accept: 'application/json',
                    },
                    body: JSON.stringify({ query, variables }),
                }).then(r => {
                    return r.json();
                });
            }
        </script>
    </body>
</html>
